package core1.ch14thread;

import java.util.*;
import java.io.*;
import java.net.*;

public class ServerThread implements Runnable {
	Vector m_threads;

	Socket m_socket = null;

	DataInputStream m_in = null;

	DataOutputStream m_out = null;

	int m_nid;

	public ServerThread(Socket s, Vector threads) {
		m_socket = s;
		m_threads = threads;
		try {
			m_in = new DataInputStream(m_socket.getInputStream());
			m_out = new DataOutputStream(m_socket.getOutputStream());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public void write(String msg) {
		synchronized (m_out) {
			try {
				m_out.writeUTF(msg);
			} catch (Exception e) {

			}
		}
	}

	public int getID() {
		return m_nid;
	}

	public void setID(int nid) {
		m_nid = nid;
	}

	public void run() {
	
		System.out.println("Thread is running...");
		try {
			while(true){
				String s= m_in.readUTF();
				if (s==null) {
					break;
				}
				if (s.trim().equals("leave")) {
					for (int i = 0; i < m_threads.size(); i++) {
						ServerThread st= (ServerThread)m_threads.elementAt(i);
						st.write("***"+getID()+"leave..."+"***");
					}
				} 
				else {
					for (int i = 0; i < m_threads.size(); i++) {
						ServerThread st =(ServerThread)m_threads.elementAt(i);
						st.write("<"+getID()+">"+s);
					}
				}
			}
		} catch (Exception e) {
	
			e.printStackTrace();
		}
		m_threads.remove(this);
		try {
			m_socket.close();
		} catch (Exception e) {
	
		}
	}
}
